package com.hertz.alarm.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.hertz.alarm.dao.EhCacheDao;
import com.hertz.alarm.entity.IrisNbaAlarm;
import com.hertz.alarm.entity.IrisTrigger;
import com.hertz.alarm.entity.MatchNba;
import com.hertz.alarm.service.EntityService;
import com.hertz.alarm.service.FetchNbaData;
import com.hertz.alarm.service.IrisNbaAlarmService;
import com.hertz.alarm.service.MatchNbaService;
import com.hertz.alarm.service.SystemTriggers;
import com.hertz.alarm.util.Constants4Ehcache;
import com.hertz.alarm.util.ConstantsType;
import com.hertz.alarm.util.DateUtils;
@Service
public class SystemTriggersImpl extends BaseServiceImpl implements SystemTriggers {
	public Logger logger = LoggerFactory.getLogger(SystemTriggersImpl.class);
	@Resource
	public FetchNbaData fetchNbaData;
	@Resource
	public MatchNbaService matchNbaService;
	@Resource
	private EntityService entityService;
	@Resource
	private EhCacheDao ehcacheDao;
	@Resource
	private IrisNbaAlarmService irisNbaAlarmService;
	@Override
	public void fetchMatchData(String ymd) {
		List<MatchNba> lists = matchNbaService.listByYmd(ymd);
		boolean flag = true;
		IrisTrigger irisTrigger = entityService.getById((short)1, IrisTrigger.class);
		irisTrigger.setFlag(true);
		update(irisTrigger);
		while (flag) {
			flag = false;
			irisTrigger = entityService.getById((short)1, IrisTrigger.class);
			if(irisTrigger.getFlag()){
				for(MatchNba item : lists){
					MatchNba matchNba = matchNbaService.getBySourceId(item.getSourceId());
					if(matchNba != null && matchNba.getPeriod() < 0){
						logger.info("match is end,source_id:{}",matchNba.getSourceId());
					}else{
						flag = true;
						fetchNbaData.fetchCurrentMatchData(item.getSourceId());
					}
					logger.debug("##############################################");
				}
				logger.debug("=========================================================================================================");
				logger.debug("=========================================================================================================");
				try {
					Thread.sleep(30*1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}else{
				logger.debug("irisTrigger id=1 flag == false");
				break;
			}
		}
		irisTrigger.setFlag(false);
		update(irisTrigger);

	}
	@Override
	public List<IrisTrigger> listALl() {
		return baseDAO.listAll(IrisTrigger.class);
	}
	
	@Override
	public void update(IrisTrigger irisTrigger) {
		ehcacheDao.update(String.format(Constants4Ehcache.KEY_TRIGGER, irisTrigger.getId()), irisTrigger, Constants4Ehcache.REGION_TRIGGER);
		entityService.update(irisTrigger);
		
	}
	@Override
	public void fetchMatchDataTimer() {
		logger.info("start fetchMatchDataTimer");
		String today = DateUtils.today(DateUtils.Y_M_D);
		List<MatchNba> matchs = matchNbaService.listByYmd(today);
		if(matchs == null || matchs.size() == 0){
			logger.info("no matchs,today");
			return;
		}else{
			IrisTrigger irisTrigger = entityService.getById((short)1, IrisTrigger.class);
			if(irisTrigger.getFlag()){
				logger.info("fetchMatchData is running,so return");
				return ;
			}else{
				for(MatchNba mn : matchs){
					if(mn.getPeriod() != ConstantsType.MATCH_PERIOD.END.getValue()){
						fetchMatchData(today);
						return;
					}
				}
				return;
			}
			
		}
	}
	
	
	@Override
	@PostConstruct
	public void startSystem() {
		// TODO Auto-generated method stub
		IrisTrigger irisTrigger = entityService.getById((short)1, IrisTrigger.class);
		irisTrigger.setFlag(false);
		update(irisTrigger);
		
		Calendar c = Calendar.getInstance();
		String day = DateUtils.timeFormat(c.getTimeInMillis(), DateUtils.Y_M_D);
		List<IrisNbaAlarm> irisNbaAlarms = irisNbaAlarmService.listAllFromMtimeFromDb(day);
		if(irisNbaAlarms != null && irisNbaAlarms.size() != 0){
			for(IrisNbaAlarm irisNbaAlarm : irisNbaAlarms){
				ehcacheDao.save(String.format(Constants4Ehcache.KEY_MATCH_ALARM_ID, irisNbaAlarm.getId()), irisNbaAlarm, Constants4Ehcache.REGION_MATCH_ALARM);
				List<Long> list = (ArrayList<Long>)ehcacheDao.get(String.format(Constants4Ehcache.KEY_MATCH_ALARM_UID_YMD, irisNbaAlarm.getUid(),DateUtils.timeFormat(irisNbaAlarm.getMatchTime(),DateUtils.Y_M_D)), Constants4Ehcache.REGION_MATCH_ALARM);
				if(list == null){
					list = new ArrayList<Long>();
				}
				if(!list.contains(irisNbaAlarm.getId()))
					list.add(irisNbaAlarm.getId());
				ehcacheDao.update(String.format(Constants4Ehcache.KEY_MATCH_ALARM_UID_YMD, irisNbaAlarm.getUid(),DateUtils.timeFormat(irisNbaAlarm.getMatchTime(),DateUtils.Y_M_D)),list, Constants4Ehcache.REGION_MATCH_ALARM);
				ehcacheDao.save(String.format(Constants4Ehcache.KEY_MATCH_ALARM_UID_MID, irisNbaAlarm.getUid(),irisNbaAlarm.getMid()), irisNbaAlarm.getId(), Constants4Ehcache.REGION_MATCH_ALARM);
			}
		}
		
		int days = 7;
		for(int i = 0; i < days; i++){
			c = Calendar.getInstance();
			c.add(Calendar.DATE, i);
			day = DateUtils.timeFormat(c.getTimeInMillis(), DateUtils.Y_M_D);
			matchNbaService.listByYmd(day);
		}
		
		
	}
	@Override
	@PreDestroy
	public void shutDownSystem(){
//		IrisTrigger irisTrigger = entityService.getById((short)1, IrisTrigger.class);
//		irisTrigger.setFlag(false);
//		entityService.update(irisTrigger);
	}
	
}
